import Vue from 'vue'
import Vuex from 'vuex'
import { Login, GetMenu } from "../api/admin";
import { Message } from 'element-ui'
//import { setToken } from '../utility/auth';
import Cookies from 'js-cookie'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: '',
    menu: []
  },
  getters: {
    menu: state => state.menu,
    token: state => state.token
  },
  //同步修改Vuex数据
  mutations: {
    SetToken(state, token) {
      state.token = token;
    },
    SetMenu(state, menu) {
      state.menu = menu;
    }
  },
  actions: {
    Login({ commit }, data) {
      let { userName, password } = data;
      return new Promise((resolve, reject) => {
        //调WebApi接口
        Login({ username: userName, password: password }).then(m => {
          if (m.data.loginState != 200) {
            Message({
              message: m.data.msg,
              type: 'error',
              duration: 5 * 1000
            })
            reject(m.data);
          } else {
            //解构
            let { token } = m.data;
            //存Vue.ls
            Vue.ls.set('token', token, 60 * 60 * 1000 * 24);
            //存Cookies
            //setToken(token);

            //存Vuex
            commit('SetToken', token);
            resolve();
          }
        }).catch(error => {
          reject();
        });
      })
    },
    GetMenu({ commit }) {
      //获取菜单
      return new Promise((resolve, reject) => {
        GetMenu().then(m => {
          let { data } = m.data;

          Vue.ls.set('menu', data, 60 * 60 * 1000 * 24);
          commit('SetMenu', data);
          //Cookies.set('menu', JSON.stringify(data));
          resolve(data);
        });
      });
    }
  },
  modules: {
  }
})